﻿using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.IO;
using UDS.Management.Data.Package;
using UDS.Build.Database.Replication;

namespace UDS.Build.Database
{
    public class GenerateReplicationSproc : Task
    {
        private PublicationDefinition publications;

        [Required]
        public string ReplicationSproc
        {
            get;
            set;
        }

        [Required]
        public ITaskItem[] PublicationDefinition
        {
            get;
            set;
        }

        public override bool Execute()
        {
            LoadPublicationDefinitions();
            Log.LogMessage(MessageImportance.High, "Building replication stored procedures for replication version {0} in file {1}", publications.Version, ReplicationSproc);
            publications.GenerateSQL(ReplicationSproc);
            return true;
        }

        private void LoadPublicationDefinitions()
        {
            publications = new PublicationDefinition();
            ReplXMLHelper replLoader = new ReplXMLHelper();
            foreach (ITaskItem pubItem in PublicationDefinition)
            {
                Stream stm = File.OpenRead(pubItem.ItemSpec);
                using (ScriptSource src = new ScriptSource(pubItem.ItemSpec, stm))
                {
                    publications.Load(replLoader.Load(src));
                }
            }
        }
    }
}
